



export let OTA_CMD_NVDS_TYPE = 0;
export let  OTA_CMD_GET_STR_BASE = 1;
export let  OTA_CMD_PAGE_ERASE = 3;
export let  OTA_CMD_CHIP_ERASE = 4;
export let  OTA_CMD_WRITE_DATA = 5;
export let  OTA_CMD_READ_DATA = 6;
export let  OTA_CMD_WRITE_MEM = 7;
export let  OTA_CMD_READ_MEM  = 8;
export let  OTA_CMD_REBOOT = 9;
export let  OTA_CMD_NULL = 10;


export function cmd_write_op(opcode,length,addr,datalenth) {
  let  cmd = [];
  if(opcode == OTA_CMD_PAGE_ERASE){
    cmd = new Array(7);
  }else{
    cmd = new Array(9);
  }
  cmd[0] =  intToByte(opcode&0xff);
  cmd[1] =  intToByte(length&0xff);
  cmd[2] =  intToByte((length&0xff) >> 8);
  cmd[3] = intToByte(addr&0xff);
  cmd[4] =  intToByte((addr&0xff00) >> 8);
  cmd[5] =  intToByte((addr&0xff0000) >> 16);
  cmd[6] =  intToByte((addr&0xff000000) >> 24);
  if(opcode != OTA_CMD_PAGE_ERASE){
    cmd[7] =  intToByte(datalenth&0xff);
    cmd[8] =  intToByte((datalenth&0xff00)>>8);
  }
  return cmd;
}

//整数转字节
export function intToByte(i) {
  var b = i & 0xFF;
  var c = 0;
  if (b >= 128) {
    c = b % 128;
    c = -1 * (128 - c);
  } else {
    c = b;
  }
  return c
}



//命令转换
export function cmd_operation(type, lenth, addr) {
  let cmd = [];

  if((type == OTA_CMD_WRITE_MEM) || (type == OTA_CMD_WRITE_DATA)){
    cmd = cmd_write_op(type,9,addr,lenth);
  }else if((type  == OTA_CMD_GET_STR_BASE) || (type  == OTA_CMD_NVDS_TYPE)){
    cmd = cmd_write_op(type,3,0,0);
  }else if(type == OTA_CMD_PAGE_ERASE){
    cmd = cmd_write_op(type,7,addr,0);
  }
  return cmd;
}

// let cmd_write = cmd_operation(5,500,131072);
//
// console.log(cmd_write)


//获取要发送的命令
export function send_data(type, addr, buffer, length) {
  let result_cmd = []
  let cmd = []
  let cmd_write = cmd_operation(type,length,addr);
  if((type  == OTA_CMD_GET_STR_BASE) || (type  == OTA_CMD_PAGE_ERASE) || (type  == OTA_CMD_NVDS_TYPE)){
    result_cmd = cmd_write;
  }else if(type  == OTA_CMD_REBOOT){
    cmd[0] = intToByte(type&0xff);
    result_cmd = cmd;
  }else{
    result_cmd = cmd_write.concat(buffer)
  }

  return result_cmd
}


// let a = send_data(5, 131072, [0, 0, 0, 0], 500 )
//
//
// console.log(a)


//字节数组转整数
export function bytetoint(data){
  let addr;
  addr = (data[4] & 0x000000ff);
  addr |= ((data[5] & 0x0000ff) << 8);
  addr |= ((data[6] & 0x000000ff) << 16);
  addr |= ((data[7] & 0x000000ff) << 24);
  return addr;
}


export function bytetochar(data) {
  let value;
  value = ((data[4] & 0x000000ff));
  return value;
}

